import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/create_user/user_course_class/course_class_bean/course_class_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/user_select_sort_save_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

class CourseClassWidget extends StatefulWidget {
  final List<CourseClassListItemBean> selectCourseListBeanIndex;
  const CourseClassWidget({Key key, this.selectCourseListBeanIndex}) : super(key: key);

  @override
  _CourseClassWidgetState createState() => _CourseClassWidgetState();

  ///跳转方法
  static Future<List<CourseClassListItemBean>> navigatorPush(BuildContext context,List<CourseClassListItemBean> selectCourseListBean) {
    return RouterUtils.routeForFutureResult<List<CourseClassListItemBean>>(
      context,
      CourseClassWidget(
          selectCourseListBeanIndex:selectCourseListBean
      ),
    );
  }
}

class _CourseClassWidgetState extends State<CourseClassWidget> {
  List<CourseClassListItemBean> mList;
  final String _courseType = "02";
  bool isLightUp = false; //确认按钮是否亮起
  List<String> selectCourseIndex = new List(); //选中的行
  List<TextEditingController> _editCourseListController = new List<TextEditingController>();
  List<CourseClassListItemBean> listCourseItemBean = new List();
  // TextEditingController _editCourseController;
  List<CourseClassListItemBean> mAddRecordCourseList = List();

  List<CourseClassListItemBean> selectListCourseItemBean = new List();

  CommonListPageWidgetState mState;

  // @override
  // void initState() {
  //   super.initState();
  //   _editCourseController = TextEditingController();
  // }
  // @override
  // void dispose() {
  //   _editCourseController.dispose();
  //   super.dispose();
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            // color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            _toTopBarWidget(),
            Padding(
              padding: const EdgeInsets.only(left: 7, right: 7, top: 10),
              child: _searchDepartmentWidget(),
            ),
            SizedBox(
              height: 10,
            ),
            //点击添加一行
            _addCourseListWidget(),
            //课程list
            _courseClassListWidget(),
          ],
        ),
      ),
    );
  }

  Widget _courseClassListWidget() {
    Widget divider = Divider(
      color: Colors.blue,
    );
    return Expanded(
      child: CommonListPageWidget<CourseClassListItemBean, ClassCourseBean>(
        enablePullUp: false,
        enablePullDown: true,
        queryMapFunc:(int page) => {
          "authId": UserRepository.getInstance().authId ?? "",
          "name":"",
          "type": _courseType,
        },
        parseDataFunc: (VgHttpResponse resp) {
          ClassCourseBean bean = ClassCourseBean.fromMap(resp?.data);
          bean?.data?.removeWhere((element) =>
              element == null ||
              StringUtils.isEmpty(element.id) ||
              StringUtils.isEmpty(element.name));
          return bean;
        },
        listFunc: (List<CourseClassListItemBean> courseList) {
          if(widget?.selectCourseListBeanIndex?.length !=0 && widget?.selectCourseListBeanIndex != null){
            widget?.selectCourseListBeanIndex?.forEach((element) {
              selectCourseIndex.add(element?.id);
            });
          }
          mList = courseList;
          if(mAddRecordCourseList.length>0){
            mAddRecordCourseList.forEach((element) {
              // if(element?.name!=""&&element?.name!=null){
              //
              // }
              mList?.insert(0, element);
            });
          }

          mList.forEach((element) {
            element.isSelect = false;
          });
          if (selectCourseIndex == null || selectCourseIndex.isEmpty) {
            return;
          }
          for (CourseClassListItemBean itemBean in mList) {
            if (itemBean?.id == null || itemBean.id.isEmpty) {
              continue;
            }
            if (selectCourseIndex.indexOf(itemBean.id) != -1) {
              itemBean.isSelect = true;
            }
          }
          if(_editCourseListController == null || _editCourseListController.isEmpty){
            return;
          }
          _editCourseListController?.forEach((controller) {
            CourseClassListItemBean addItemBean = CourseClassListItemBean();
            addItemBean.isEdit = true;
            addItemBean.controller = controller;
            mList?.insert(0, addItemBean);
            mAddRecordCourseList.add(addItemBean);
          });

        },
        stateFunc: (CommonListPageWidgetState state) {
          mState = state;
        },
        itemBuilder: (BuildContext context, int index,
            CourseClassListItemBean itemBean) {
          if (itemBean == null) return Container();

          if (itemBean?.isEdit ?? false) {
            return _addCourseListRow(context, index, itemBean);

          }

          return _toListItemWidget(context, index, itemBean);
        },
        //分割器构造器
        separatorBuilder: (context, int index, _) {
          return Container(
            height: 0.5,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            padding: const EdgeInsets.only(left: 15),
            child: Container(
              color: Color(0xFF303546),
            ),
          );
          // return divider;
        },
        placeHolderFunc: (List<CourseClassListItemBean> list,Widget child,VoidCallback onRefresh){
          return VgPlaceHolderStatusWidget(
            emptyStatus: list == null || list.isEmpty,
            emptyOnClick: () => onRefresh(),
            child: child,
          );
        },
        netUrl:ServerApi.BASE_URL + "app/appChooseInfo",
        httpType: VgHttpType.post,
      ),
    );
  }

  Widget _addCourseListRow(
      BuildContext context, int index, CourseClassListItemBean itemBean) {

    return GestureDetector(
      onTap: () {
        itemBean?.isSelect = !itemBean?.isSelect;
        setState(() {});
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 10,
            ),
            Image(
              image: itemBean?.isSelect ?? false
                  ? AssetImage("images/common_unselect_ico.png")
                  : AssetImage("images/common_selected_ico.png"),
              width: 20,
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: VgTextField(
                maxLines: 1,
                controller: itemBean.controller,
                onChanged: (String editCourse){
                  // itemBean?.name= _editCourseController?.text;
                  // print("输出长度：${_editCourseListController.length}");
                  String editListText = "";
                  for(TextEditingController item in _editCourseListController){
                    editListText += item.text.toString();
                  }
                  if(_editCourseListController.length!=0 && editListText.trim()!=null && editListText.trim()!=""){
                    isLightUp=true;
                  }else{isLightUp=false;}
                  setState(() {

                  });
                },
                decoration: InputDecoration(
                  border: InputBorder.none,
                  counterText: "",
                  contentPadding: const EdgeInsets.only(bottom: 2),
                  hintText: "请输入课程名",
                  hintStyle: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getTextEditHintColor_3A3F50(),
                      fontSize: 14),
                ),
                style: TextStyle(
                    fontSize: 14,
                    color: ThemeRepository.getInstance()
                        .getTextMainColor_D0E0F7()),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, CourseClassListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        itemBean.isSelect ? isLightUp= false : isLightUp = true;
        itemBean.isSelect = !itemBean.isSelect;
        if (itemBean.isSelect) {
          selectCourseIndex.add(itemBean.id);
          selectListCourseItemBean.add(itemBean);
        } else {
          selectCourseIndex.remove(itemBean.id);
          selectListCourseItemBean.remove(itemBean);
        }
        print(selectCourseIndex.toString());
        setState(() {});
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 10,
            ),
            Image(
              image: itemBean.isSelect ?? false
                  ? AssetImage("images/common_selected_ico.png")
                  : AssetImage("images/common_unselect_ico.png"),
              width: 20,
            ),
            SizedBox(
              width: 10,
            ),
            Text(
              itemBean?.name ?? "",
              style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }

  Widget _editCourseWidget() {
    return Container(
      height: 50,
      color: Colors.redAccent,
      child: VgTextField(),
    );
  }

  Widget _addCourseListWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        _addRowCourse();
      },
      child: Container(
        height: 50,
        padding: const EdgeInsets.only(left: 7),
        alignment: Alignment.centerLeft,
        child: Text(
          "+添加",
          style: TextStyle(color: Color(0xFF1890FF), fontSize: 14),
          textAlign: TextAlign.left,
        ),
      ),
    );
  }

  void _addRowCourse() {
    TextEditingController _editCourseController = new TextEditingController();
    CourseClassListItemBean addItemBean = CourseClassListItemBean();
    addItemBean.isEdit = true;
    addItemBean.controller = _editCourseController;

    _editCourseListController.insert(0, _editCourseController);
    mList?.insert(0, addItemBean);
    mAddRecordCourseList?.add(addItemBean);
    mState?.data = mList;
    mState.setState(() { });
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "课程",
      rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: isLightUp,
        width: 48,
        height: 24,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          if (isLightUp) {
            _httpSave();
          }
        },
      ),
    );
  }

  void _httpSave(){
    // List<CourseClassListItemBean> mList;
    if(_editCourseListController!=null&&_editCourseListController?.length>0){
      String textList = "";
      for (int i = 0; i < _editCourseListController?.length; i++) {
        if (_editCourseListController[i]?.text?.trim() == "") {
          _editCourseListController.removeAt(i);
        }
      }
      for (int i = 0; i < _editCourseListController?.length; i++) {
        if (_editCourseListController?.length != 0) {
          textList += _editCourseListController[i]?.text?.trim() + ",";
        }
      }
      if(textList==""){
        if(_editCourseListController?.length==0){
          if(selectListCourseItemBean?.length!=0 && selectListCourseItemBean!=null){
            for(int i = 0; i<selectListCourseItemBean?.length;i++){
              if(selectListCourseItemBean[i]?.name==""){
                selectListCourseItemBean?.removeAt(i);
              }
              listCourseItemBean.add(selectListCourseItemBean[i]);
            }
          }
          return RouterUtils.pop(context,result: listCourseItemBean);
        }
      }

      VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddChooseInfo",
          params: {
            "authId": UserRepository.getInstance().authId ?? "",
            "name": textList?.substring(0,textList.length -1) ?? "",
            "type": _courseType,
          },
          callback: BaseCallback(onSuccess: (dynamic val) {
            UserSelectSortSaveResponseBean successBean =
            UserSelectSortSaveResponseBean.fromMap(val);
            if (successBean == null ||
                successBean.data == null ||
                successBean.data.isEmpty) {
              VgToastUtils.toast(context, "课程添加返回值错误");
              return;
            }
            if(selectListCourseItemBean?.length!=0 && selectListCourseItemBean!=null){
              for(int i = 0; i<selectListCourseItemBean?.length;i++){
                listCourseItemBean.add(selectListCourseItemBean[i]);
              }
            }

            successBean.data.forEach((element) {
              CourseClassListItemBean classCourseListItemBean =
              CourseClassListItemBean();
              classCourseListItemBean?.name=element?.name;
              classCourseListItemBean?.id=element?.id;
              listCourseItemBean.add(classCourseListItemBean);
            });
            //接收数据，selectCourseIndex进行for循环对比，拿出选中的指返回给上一界面
            VgToastUtils.toast(context, "保存成功");
            RouterUtils.pop(context,result: listCourseItemBean);
          }, onError: (String e) {
            VgToastUtils.toast(context, "添加数据错误");
            return;
          }));
    }
    if(selectListCourseItemBean?.length!=0 && selectListCourseItemBean!=null){
      for(int i = 0; i<selectListCourseItemBean?.length;i++){
        listCourseItemBean.add(selectListCourseItemBean[i]);
      }
    }
    VgToastUtils.toast(context, "保存成功");
    RouterUtils.pop(context,result: listCourseItemBean);
    // for(CourseClassListItemBean item in mList){
    //   print("gz2:::${item.name} :: ${item.id}  ::  ${item.isSelect} ::  ${item.isEdit}");
    // }
  }

  Widget _searchDepartmentWidget() {
    return Container(
      height: 30,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        contentPadding: EdgeInsets.only(top: 0,bottom: 15),
        hintText: "搜索",
        customIcon: "images/common_search_ico.png",
        iconColor: Colors.white54,
        onChanged: (String cityText) {
          //搜索
        },
      ),
    );
  }
}
